package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.controller.admin.EmployeeController;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.handler.GlobalExceptionHandler;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();
        //mapper层最好还是传实体类而不是DTO，所以这里是把DTO转实体类
        //ps,因为dto属性要少，而数据库表是对应着实体类的（这个才是重点），增删改查数据库表肯定要拿实体类改，所以mapper层拿到的必须是entity
        BeanUtils.copyProperties(employeeDTO,employee);
        //做了修改以后要设置修改人和修改时间
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 修改员工查询回显
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee=employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO0
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO0) {
        PageHelper.startPage(employeePageQueryDTO0.getPage(),employeePageQueryDTO0.getPageSize());
        Page<Employee> page=employeeMapper.page(employeePageQueryDTO0);//返回类型是固定的，pagehelper插件的Page类型
        //pagehelper插件自己有获取总记录数total和该页记录数records的api
//        page.getTotal();
        return new PageResult(page.getTotal(),page.getResult());//将返回值类型转为了PageResult
    }

    /**
     * 启用禁用员工
     * @param status
     * @param id
     */
    @Override
    public void startorstop(Integer status, Long id) {

//        employeeMapper.startorstop(status,id);
        Employee employee =new Employee();
        employee.setId(id);
        employee.setStatus(status);

        employeeMapper.startorstop(employee);
    }

    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO//要实现这样一个DTO！
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 若进行MD5码加密，数据库中存放的得是密文形式的password
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * add a employee(这里是写真正业务逻辑的地方！！！）
     * @param employeeDTO0
     */
    @Override
    public void saveEmployee(EmployeeDTO employeeDTO0) {
        //原来是dto中get过来set到实体中，这里直接属性拷贝（mapper层）
        Employee employee0=new Employee();
//        employee0.setId(employeeDTO0.getId());
        BeanUtils.copyProperties(employeeDTO0,employee0);//这里转到mapper层为什么要dto转实体类呢？可能是为了方便数据库操作

//        //上面查完下面这里再异常处理逻辑,用try-catch捕捉异常
//        try(employeeMapper.getByUsername(employee0.getUsername())){
//
//        }catch{
//
//        }

        employee0.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        employee0.setStatus(StatusConstant.ENABLE);

//        employee0.setCreateTime(LocalDateTime.now());
//        employee0.setUpdateTime(LocalDateTime.now());
//        JwtUtil.parseJWT()
//        employee0.setCreateUser(BaseContext.getCurrentId());
//        employee0.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.saveEmployee(employee0);
    }

}
